<template>
    <div class="leave-request-list">
        <h1 class="page-title">请假申请列表</h1>
        <el-form :model="queryDTO" class="search-form" label-width="0">
            <el-row :gutter="20" justify="center">
                <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item>
                        <el-input
                            v-model="queryDTO.elderlyUserId"
                            placeholder="老人用户ID"
                            @change="validateElderlyUserId"
                            @keyup.native="filterNonNumber"
                            clearable
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item>
                        <el-select v-model="queryDTO.reasonType" placeholder="全部类型">
                            <el-option label="全部类型" value=""></el-option>
                            <el-option label="病假" value="medical"></el-option>
                            <el-option label="探亲假" value="family_reunion"></el-option>
                            <el-option label="个人事假" value="personal_affairs"></el-option>
                            <el-option label="其他" value="other"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item>
                        <el-select v-model="queryDTO.status" placeholder="全部状态">
                            <el-option label="全部状态" value=""></el-option>
                            <el-option label="申请中" value="pending"></el-option>
                            <el-option label="允许" value="approved"></el-option>
                            <el-option label="拒绝" value="rejected"></el-option>
                            <el-option label="取消" value="cancelled"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item>
                        <el-button type="primary" @click="fetchLeaveRequests">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-card v-if="loading" class="loading-card">
            <div class="loading-content">加载中...</div>
        </el-card>
        <el-card v-else>
            <el-table :data="leaveRequests" stripe border>
                <!-- 申请序号列，设置合适宽度，如80 -->
                <el-table-column prop="id" label="申请序号" sortable @sort-change="sortBy('id')" width="110"></el-table-column> 
                <!-- 老人用户ID列，设置合适宽度，如100 -->
                <el-table-column prop="elderlyUserId" label="老人用户ID" sortable @sort-change="sortBy('elderlyUserId')" width="120"></el-table-column> 
                <el-table-column prop="reasonType" label="请假类型" sortable @sort-change="sortBy('reasonType')">
                    <template #default="{ row }">
                        {{ getReasonDisplay(row) }}
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" sortable @sort-change="sortBy('startTime')"></el-table-column>
                <el-table-column prop="endTime" label="结束时间" sortable @sort-change="sortBy('endTime')"></el-table-column>
                <el-table-column prop="status" label="状态" sortable @sort-change="sortBy('status')">
                <template #default="{ row }">
                    {{ getStatusDisplay(row.status) }}
                </template>
                </el-table-column>
                <!-- 操作列，设置足够宽度让按钮同行，如180 -->
                <el-table-column label="操作" width="180"> 
                <template #default="{ row }">
                    <div class="action-buttons">
                        <el-button v-if="row.status === 'pending'" @click="cancelPending(row.id)" type="danger" size="small" style="margin-right: 10px;">拒绝</el-button>
                        <el-button v-if="row.status === 'pending'" @click="approvalPending(row.id)" type="success" size="small">批准</el-button>
                        <el-button v-if="row.status === 'on_leave'" @click="submitCancelApproved(row.id)" type="warning" size="small">允许取消</el-button>
                    </div>
                </template>
                </el-table-column>
            </el-table>
            <div v-if="leaveRequests.length === 0" class="no-data">暂无数据</div>
        </el-card>
        <!-- 分页区域调整后 -->
        <div v-if="leaveRequests.length > 0" class="pagination-wrapper">
            <div class="pagination-left custom-pagination-left">
                <span>共{{ totalPages * queryDTO.pageSize }}条</span>
                <el-select v-model="queryDTO.pageSize" placeholder="条数/页" @change="handleSizeChange" style="margin-left: 8px;">
                    <el-option label="10条/页" value="10"></el-option>
                    <el-option label="20条/页" value="20"></el-option>
                    <el-option label="30条/页" value="30"></el-option>
                </el-select>
            </div>
            <div class="pagination-middle">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30]"
                    :page-size="queryDTO.pageSize"
                    layout="prev, pager, next" 
                    :total="totalPages * queryDTO.pageSize">
                </el-pagination>
            </div>
            <div class="pagination-right">
                前往 
                <input type="number" v-model.number="gotoPage" min="1" max="totalPages" style="width: 60px; margin: 0 5px;"> 
                页
                <el-button type="primary" size="mini" @click="gotoSpecifiedPage">确认</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { listLeaveRequests, cancelPendingLeaveRequest, submitCancelApprovedLeaveRequest, reviewCancelRequest, reviewLeaveRequest } from '../../../api/LeaveRequest.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const adminId = localStorage.getItem('adminId');

const queryDTO = ref({
    elderlyUserId: null,
    reasonType: '',
    status: '',
    pageNo: 1,
    pageSize: 10
});

const leaveRequests = ref([]);
const totalPages = ref(1);
const currentPage = ref(1);
const sortField = ref('id');
const sortDirection = ref('asc');
const loading = ref(false);
const gotoPage = ref(1);

watch(totalPages, () => {
    gotoPage.value = Math.min(gotoPage.value, totalPages.value);
});

const getReasonDisplay = (request) => {
    const reasonMap = {
        'medical': '病假',
        'family_reunion': '探亲假',
        'personal_affairs': '个人事假',
        'other': request.reasonDetails || '其他'
    };
    return reasonMap[request.reasonType] || request.reasonType;
};

const getStatusDisplay = (status) => {
    const statusMap = {
        'pending': '待处理',
        'approved': '已批准',
        'rejected': '已拒绝',
        'cancelled': '已取消',
        'on_leave': '取消待批准',
        'completed': '已销假',
    };
    return statusMap[status] || status;
};

const formatDateTime = (dateTimeString) => {
    if (!dateTimeString) return '';
    return dateTimeString.replace('T', ' ');
};

const fetchLeaveRequests = async () => {
    loading.value = true;
    try {
        console.log('查询参数:', queryDTO.value);
        const response = await listLeaveRequests(queryDTO.value);
        leaveRequests.value = response.list;
        totalPages.value = Math.ceil(response.total / queryDTO.value.pageSize);
        ElMessage.success('查询成功');
    } catch (error) {
        console.error('查询失败:', error);
        if (error.response) {
            console.log('响应状态码:', error.response.status);
            console.log('响应数据:', error.response.data);
        } else if (error.request) {
            console.log('请求已发送，但没有收到响应:', error.request);
        } else {
            console.log('发生错误:', error.message);
        }
        ElMessage.error('查询失败：' + (error.response?.data?.message || '未知错误'));
    } finally {
        loading.value = false;
    }
};

const cancelPending = async (id) => {
    try {
        await ElMessageBox.confirm('确定要拒绝这个请假申请吗？', '确认拒绝', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        await reviewLeaveRequest(id, false, 1);
        ElMessage.success('拒绝成功');
        fetchLeaveRequests();
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消操作');
        } else {
            console.error('拒绝失败:', error);
            ElMessage.error('拒绝失败：' + (error.response?.data?.message || '未知错误'));
        }
    }
};

const approvalPending = async (id) => {
    try {
        await ElMessageBox.confirm('确定要批准这个请假申请吗？', '确认批准', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
        });
        
        await reviewLeaveRequest(id, true, 1);
        ElMessage.success('批准成功');
        fetchLeaveRequests();
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消操作');
        } else {
            console.error('批准失败:', error);
            ElMessage.error('批准失败：' + (error.response?.data?.message || '未知错误'));
        }
    }
};

const submitCancelApproved = async (id) => {
    try {
        await ElMessageBox.confirm('确定要允许取消这个请假申请吗？', '确认允许取消', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        await reviewCancelRequest(id, true, 1);
        ElMessage.success('允许取消成功');
        fetchLeaveRequests();
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消操作');
        } else {
            console.error('批准取消申请失败:', error);
            ElMessage.error('批准取消申请失败：' + (error.response?.data?.message || '未知错误'));
        }
    }
};

const sortBy = (field) => {
    if (sortField.value === field) {
        sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
    } else {
        sortField.value = field;
        sortDirection.value = 'asc';
    }
    queryDTO.value.sortField = sortField.value;
    queryDTO.value.sortDirection = sortDirection.value;
    fetchLeaveRequests();
};

const handleSizeChange = (newSize) => {
    queryDTO.value.pageSize = newSize;
    queryDTO.value.pageNo = 1; 
    currentPage.value = 1;
    fetchLeaveRequests();
};

const handleCurrentChange = (newPage) => {
    queryDTO.value.pageNo = newPage;
    currentPage.value = newPage;
    fetchLeaveRequests();
};

const validateElderlyUserId = () => {
    const value = queryDTO.value.elderlyUserId;
    if (value === '' || value === null) {
        return;
    }
    const numberValue = parseInt(value, 10);
    if (!isNaN(numberValue) && numberValue > 0) {
        queryDTO.value.elderlyUserId = numberValue;
    } else {
        queryDTO.value.elderlyUserId = null;
        ElMessage.warning('老人用户ID必须为正整数');
    }
};

const filterNonNumber = (e) => {
    e.target.value = e.target.value.replace(/[^0-9]/g, '');
    queryDTO.value.elderlyUserId = e.target.value || null;
};

const gotoSpecifiedPage = () => {
    if (gotoPage.value < 1 || gotoPage.value > totalPages.value) {
        ElMessage.warning('请输入有效的页码');
        return;
    }
    queryDTO.value.pageNo = gotoPage.value;
    currentPage.value = gotoPage.value;
    fetchLeaveRequests();
};

onMounted(fetchLeaveRequests);
</script>

<style scoped>
.leave-request-list {
    background-color: #f9f9f9;
    padding: 20px;
    width: 99%;
    height: 750px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.page-title {
    text-align: center;
    margin-bottom: 20px;
    color: #333;
    font-size: 24px;
}

.search-form {
    margin-bottom: 20px;
}

.loading-card {
    text-align: center;
    color: #007bff;
    padding: 20px;
}

.loading-content {
    font-size: 16px;
}

.no-data {
    text-align: center;
    color: #999;
    padding: 20px;
}

.pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-left {
    display: flex;
    align-items: center;
    color: #666;
}

/* 添加自定义样式 */
.custom-pagination-left {
  min-width: 200px; /* 设置最小宽度，可根据需要调整 */
  justify-content: space-between; /* 元素之间均匀分布 */
}

/* 如果需要更宽的下拉选择器 */
.custom-pagination-left .el-select {
  width: 100px; /* 可根据需要调整 */
}

.pagination-middle {
    flex: 1;
    display: flex;
    justify-content: center;
}

.pagination-right {
    display: flex;
    align-items: center;
}

.pagination-right input {
    text-align: center;
}

.pagination-right .el-button {
    margin-left: 8px;
}


.action-buttons {
  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 8px; /* 按钮之间的间距 */
}

/* 如果需要垂直居中，可以添加以下样式 */
.el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}


</style>